package it.niedermann.android.markdown.markwon.handler

import android.text.Editable
import android.text.Spanned
import io.noties.markwon.base.Markwon
import io.noties.markwon.base.core.spans.CodeBlockSpan
import io.noties.markwon.base.editor.EditHandler
import io.noties.markwon.base.editor.MarkwonEditorUtils.findDelimited
import io.noties.markwon.base.editor.PersistedSpans
import io.noties.markwon.theme.MarkwonTheme

class CodeBlockEditHandler : EditHandler<CodeBlockSpan> {
    private var theme: MarkwonTheme? = null
    override fun init(markwon: Markwon) {
        theme = markwon.configuration().theme
    }

    override fun configurePersistedSpans(builder: PersistedSpans.Builder) {
        builder.persistSpan(CodeBlockSpan::class.java, PersistedSpans.SpanFactory<CodeBlockSpan> {
            CodeBlockSpan(
                theme!!
            )
        })
    }

    override fun handleMarkdownSpan(
        persistedSpans: PersistedSpans,
        editable: Editable,
        input: String,
        span: CodeBlockSpan,
        spanStart: Int,
        spanTextLength: Int
    ) {
        val delimited = findDelimited(input, spanStart, "```")
        if (delimited != null) {
            editable.setSpan(
                persistedSpans[markdownSpanType()],
                delimited.start(),
                delimited.end(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
    }

    override fun markdownSpanType(): Class<CodeBlockSpan> {
        return CodeBlockSpan::class.java
    }
}